//
//  SMNetworkManager.m
//  Uhou_Framework
//
//  Created by Sunny on 16/1/20.
//  Copyright © 2016年 Sunny. All rights reserved.
//

#import "SMAFNetworkManager.h"
#import <AssetsLibrary/AssetsLibrary.h>

@implementation SMAFNetworkManager


+ (instancetype) allocWithZone:(struct _NSZone *)zone
{
    static SMAFNetworkManager *_manager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [super allocWithZone:zone];
    });
    return _manager;
}
/// 返回单例
+ (instancetype) sharedInstance
{
    return [[super alloc] init];
}

/**
 *   GET请求的公共方法 一下三种方法都调用这个方法 根据传入的不同参数觉得回调的方式
 *
 *   @param url           ur
 *   @param paramsDict   paramsDict
 *   @param target       target
 *   @param action       action
 *   @param delegate     delegate
 *   @param successBlock successBlock
 *   @param failureBlock failureBlock
 *   @param showHUD      showHUD
 */
+ (void)getRequstWithURL:(NSString*)url
                  params:(NSDictionary*)params
               requestId:(NSString *) requestId
                  target:(id)target
                  action:(SEL)action
                delegate:(id)delegate
            successBlock:(SMAFSuccessBlock)successBlock
            failureBlock:(SMAFFailureBlock)failureBlock
                 showHUD:(BOOL)showHUD
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:params];
    [[SMAFNetworkHandler sharedInstance] conURL:url networkType:SMAFNetWorkGET params:mutableDict requestId:requestId delegate:delegate showHUD:showHUD target:target action:action successBlock:successBlock failureBlock:failureBlock];
}


/**
 *   GET请求通过Block 回调结果
 *
 *   @param url          url
 *   @param paramsDict   paramsDict
 *   @param requestId    requestId
 *   @param successBlock  成功的回调
 *   @param failureBlock  失败的回调
 *   @param showHUD      是否加载进度指示器
 */
+ (void) getRequstWithURL:(NSString*) url
                   params:(NSDictionary*) paramsDict
                requestId:(NSString *) requestId
             successBlock:(SMAFSuccessBlock) successBlock
             failureBlock:(SMAFFailureBlock) failureBlock
                  showHUD:(BOOL) showHUD{
    
     [self getRequstWithURL:url params:paramsDict requestId:requestId target:nil action:nil delegate:nil successBlock:successBlock failureBlock:failureBlock showHUD:showHUD];
    
}
/**
 *   GET请求通过代理回调
 *
 *   @param url         url
 *   @param paramsDict  请求的参数
 *   @param requestId    requestId
 *   @param delegate    delegate
 *   @param showHUD    是否转圈圈
 */
+ (void) getRequstWithURL:(NSString*) url
                   params:(NSDictionary*) paramsDict
                requestId:(NSString *) requestId
                 delegate:(id<SMAFNetworkDelegate>) delegate
                  showHUD:(BOOL) showHUD{
    [self getRequstWithURL:url params:paramsDict requestId:requestId target:nil action:nil delegate:delegate successBlock:nil failureBlock:nil showHUD:showHUD];
}
/**
 *   get 请求通过 taget 回调方法
 *
 *   @param url         url
 *   @param paramsDict  请求参数的字典
 *   @param requestId    requestId
 *   @param target      target
 *   @param action      action
 *   @param showHUD     是否加载进度指示器
 */
+ (void)getRequstWithURL:(NSString*)url
                  params:(NSDictionary*)paramsDict
               requestId:(NSString *) requestId
                  target:(id)target
                  action:(SEL)action
                 showHUD:(BOOL)showHUD{
    [self getRequstWithURL:url params:paramsDict requestId:requestId target:target action:action delegate:nil successBlock:nil failureBlock:nil showHUD:showHUD];
}


#pragma mark - POST请求的三种回调方法
/**
 *   发送一个 POST请求的公共方法 传入不同的回调参数决定回调的方式
 *
 *   @param url           ur
 *   @param paramsDict   paramsDict
 *   @param target       target
 *   @param action       action
 *   @param delegate     delegate
 *   @param successBlock successBlock
 *   @param failureBlock failureBlock
 *   @param showHUD      showHUD
 */
+ (void)postReqeustWithURL:(NSString*)url
                    params:(NSDictionary*)params
                 requestID:(NSString *) requestId
                    target:(id)target
                    action:(SEL)action
                  delegate:(id<SMAFNetworkDelegate>)delegate
              successBlock:(SMAFSuccessBlock)successBlock
              failureBlock:(SMAFFailureBlock)failureBlock
                   showHUD:(BOOL)showHUD
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:params];
    [[SMAFNetworkHandler sharedInstance] conURL:url networkType:SMAFNetWorkPOST params:mutableDict requestId:requestId delegate:delegate showHUD:showHUD target:target action:action successBlock:successBlock failureBlock:failureBlock];
}



#pragma mark - 发送 POST 请求的方法
/**
 *   通过 Block回调结果
 *
 *   @param url           url
 *   @param paramsDict    请求的参数字典
 *   @param requestId    requestId
 *   @param successBlock  成功的回调
 *   @param failureBlock  失败的回调
 *   @param showHUD       是否加载进度指示器
 */
+ (void)postReqeustWithURL:(NSString*)url
                    params:(NSDictionary*)paramsDict
                 requestId:(NSString *) requestId
              successBlock:(SMAFSuccessBlock)successBlock
              failureBlock:(SMAFFailureBlock)failureBlock
                   showHUD:(BOOL)showHUD{
    
    [self postReqeustWithURL:url params:paramsDict requestID:requestId target:nil action:nil delegate:nil successBlock:successBlock failureBlock:failureBlock showHUD:showHUD];
    
}
/**
 *   post请求通过代理回调
 *
 *   @param url         url
 *   @param paramsDict  请求的参数
 *   @param requestId    requestId
 *   @param delegate    delegate
 *   @param showHUD    是否转圈圈
 */
+ (void)postReqeustWithURL:(NSString*)url
                    params:(NSDictionary*)paramsDict
                 requestId:(NSString *) requestId
                  delegate:(id<SMAFNetworkDelegate>)delegate
                   showHUD:(BOOL)showHUD{
    [self postReqeustWithURL:url params:paramsDict requestID:requestId target:nil action:nil delegate:delegate successBlock:nil failureBlock:nil showHUD:showHUD];
}
/**
 *   post 请求通过 target 回调结果
 *
 *   @param url         url
 *   @param paramsDict  请求参数的字典
 *   @param requestId    requestId
 *   @param target      target
 *   @param showHUD     是否显示圈圈
 */
+ (void)postReqeustWithURL:(NSString*)url
                    params:(NSDictionary*)paramsDict
                 requestId:(NSString *) requestId
                    target:(id)target
                    action:(SEL)action
                   showHUD:(BOOL)showHUD{
    [self postReqeustWithURL:url params:paramsDict requestID:requestId target:target action:nil delegate:nil successBlock:nil failureBlock:nil showHUD:showHUD];
}

/**
 *  上传文件
 *
 *  @param url          上传文件的 url 地址
 *  @param paramsDict   参数字典
 *  @param successBlock 成功
 *  @param failureBlock 失败
 *  @param showHUD      显示 HUD
 */
+ (void)uploadFileWithURL:(NSString*)url
                   params:(NSDictionary*)paramsDict
                requestId:(NSString *) requestId
             successBlock:(SMAFSuccessBlock)successBlock
             failureBlock:(SMAFFailureBlock)failureBlock
              uploadParam:(SMAFNetworkUpParam *)uploadParam
                  showHUD:(BOOL)showHUD{

    
    AFHTTPSessionManager *manager = [SMAFNetworkHandler sharedInstance].sessionManager;
    
    // 显示进度
    
    [MBProgressHUD showActiveMessageNew:@"上传中..." withBackground:YES];
    
    [manager POST:url parameters:paramsDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if (uploadParam.picDataArray.count > 0)
        {
            NSObject *firstObj = [uploadParam.picDataArray objectAtIndex:0];
            if ([firstObj isKindOfClass:[UIImage class]])
            {// 图片
                for(NSInteger i = 0; i < uploadParam.picDataArray.count; i++)
                {
                    UIImage *eachImg = [uploadParam.picDataArray objectAtIndex:i];
                    //NSData *eachImgData = UIImagePNGRepresentation(eachImg);
                    NSData *eachImgData = UIImageJPEGRepresentation(eachImg, 0.5);
                    [formData appendPartWithFileData:eachImgData name:[NSString stringWithFormat:@"img%ld", i+1] fileName:[NSString stringWithFormat:@"img%ld.jpg", i+1] mimeType:@"image/jpeg"];
                }
            }else
            {// 视频
                NSObject *firstObj = [uploadParam.videoDataArray objectAtIndex:0];
                if (firstObj != nil)
                {
                    for (int i = 0 ; i < uploadParam.videoDataArray.count; i ++) {
                        
                        ALAsset *asset = [uploadParam.videoDataArray objectAtIndex:i];
                        
                        // 获取沙盒目录
                        NSString *videoPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"video%d.mov",i]];
                        NSURL *url = [NSURL fileURLWithPath:videoPath];
                        NSError *theErro = nil;
                        /**
                         *  有问题 还没有实现方法
                         */
//                        BOOL exportResult = [asset exportDataToURL:url error:&theErro];
                        
                        NSData *videoData = [NSData dataWithContentsOfURL:url];
                        [formData appendPartWithFileData:videoData name:[NSString stringWithFormat:@"video%i",i] fileName:videoPath mimeType:@"video/quicktime"];
                        
                    }
                }
            }
        }
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
        
        response.resultDic = responseObject;
        response.resultCode = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        ITTDPRINT(@"\n\n----请求的返回结果 %@\n",responseObject);
        if (successBlock) {
            successBlock(task,response);
        }
        [MBProgressHUD dismissHUD];
        [MBProgressHUD showActiveMessage:@"上传成功！" withBackground:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
        
        if (error.userInfo[@"NSLocalizedDescription"] == NULL)
        {
            response.errorMessage = @"请求错误";
        } else
        {
            response.errorMessage = error.userInfo[@"NSLocalizedDescription"];
        }
        ITTDPRINT(@"---error==%@\n",error.localizedDescription);
        if (failureBlock) {
            failureBlock(task,response,error);
        }
        
        [MBProgressHUD dismissHUD];
        [MBProgressHUD showActiveMessage:@"上传失败" withBackground:NO];
    }];
    
}


@end
